package mqtt;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.nio.charset.StandardCharsets;

public class MqttClientTest {
    final static String topic = "/testtopic";
    final static String content = "Message from Java Client";
    final static String broker = "tcp://192.168.10.123:1883";
    final static String clientId = "mqtt_test_client";

    public static void main(String[] args) throws MqttException {
        MemoryPersistence persistence = new MemoryPersistence();
        int qos = 0;

        try {
            MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            System.out.println("Connecting to broker: " + broker);
            sampleClient.connect(connOpts);
            System.out.println("Connected");
            System.out.println("Publishing message: " + content);
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos);
            sampleClient.publish(topic, message);
            System.out.println("Message published");
            sampleClient.disconnect();
            System.out.println("Disconnected");
            System.exit(0);
        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }

    private static void testDefault() throws MqttException {
        MqttClient client = new MqttClient("localhost", "mqtt_test_client");
//        client.subscribe("testtopic");
        client.connect();
        MqttMessage msg = new MqttMessage();
        msg.setPayload("hello from java client".getBytes(StandardCharsets.UTF_8));
        client.publish("testtopic", msg);
    }

}
